#ifndef secsmart_tcpip_SERVER_H
#define secsmart_tcpip_SERVER_H

#include <memory>
#include <unordered_map>
#include <set>
#include <mutex>
#include <pthread.h>

#include "ip_addr.h"
#include "ip_filter.h"

using namespace std;

namespace secsmart_tcpip
{
enum ServerStatus {
    SERVER_DISABLE = 0,
    SERVER_ENABLE = 1,
};

enum ServerErrCode {
    SERVER_OK = 0,
    SERVER_ERROR,
};

typedef struct server_key_s {
    IPAddress ip;
    uint16_t port;
    uint8_t protocol;
    bool operator==(const server_key_s &key) const { return (ip == key.ip) && (port == key.port) && (protocol == key.protocol); }
    server_key_s(IPAddress &ip, uint16_t &port, uint8_t &protocol)
    {
        this->ip = ip;
        this->port = port;
        this->protocol = protocol;
    }
} server_key_t;

// 定义key的hash模板，用于unordered_map
typedef struct server_key_hash_s {
    uint32_t operator()(const server_key_t &key) const { return key.ip.getHash() ^ key.port ^ key.protocol; }
} server_key_hash_t;

struct Server {
    uint32_t id; // 用于配置管理
    IPAddress ip;
    uint16_t port;
    uint8_t protocol; // tcp or udp
    uint8_t status;
    IpFilter ip_filter;
};

class ServerManager
{
  public:
    ServerManager() { pthread_rwlock_init(&rwlock_, nullptr); }
    static ServerManager &get_instance()
    {
        static ServerManager instance;
        return instance;
    }
    // 初始化，订阅配置
    void init();
    void uninit();
    int add_server(IPAddress &ip, uint16_t port, uint8_t protocol, uint8_t status);
    int del_server(IPAddress &ip, uint16_t port, uint8_t protocol);
    shared_ptr<Server> get_server(IPAddress &ip, uint16_t port, uint8_t protocol);
    shared_ptr<Server> get_server(uint32_t id);
    bool find_server(IPAddress &ip, uint16_t port, uint8_t protocol);
    bool is_work_server(IPAddress &ip, uint16_t port, uint8_t protocol);
    int modify_server_status(IPAddress &ip, uint16_t port, uint8_t protocol, uint8_t status);
    int get_server_num();
    void clear_server();

  private:
    pthread_rwlock_t rwlock_; // 访问map的
    unordered_map<server_key_t, shared_ptr<Server>, server_key_hash_t> server_map_;

    // 下面两个map表用户配置管理
    // 根据server id 获取 server结构
    unordered_map<uint32_t, shared_ptr<Server>> server_id_map_;
    
    //用于管理IP过滤和server的映射，一条ip 过滤规则可以用于多个server
    unordered_map<uint32_t, set<uint32_t>> filter_server_map_;

    // 解析配置
    int parse_server_cfg(string cfg);
    int parse_ip_filter_cfg(string cfg);    
};
} // namespace secsmart_tcpip

#endif /* secsmart_tcpip_SERVER_H */
